package hku.cs.eclunuo.examples;

import hku.cs.eclunuo.util.LunuoLibHelper;
import hku.cs.lunuo.tools.DirTools;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

public class NewCreateFindMidExample extends NewCreateExample {

	public static String SRC = "FindMid/src";

	@Override
	public boolean performFinish() {
		boolean performFinish = super.performFinish();

		if (performFinish) {
			IJavaProject newProject = (IJavaProject) getCreatedElement();
			try {
				IClasspathEntry[] originalCP = newProject.getRawClasspath();
				IPath p = JavaCore.getClasspathVariable("JUNIT_HOME");
				IClasspathEntry ajrtLIB = JavaCore.newLibraryEntry(p.append("junit.jar"), null, null);//JavaCore.newContainerEntry(p);//JavaCore.newLibraryEntry(p, null, null);
				int originalCPLength = originalCP.length;
				IClasspathEntry[] newCP = new IClasspathEntry[originalCPLength + 1];
				System.arraycopy(originalCP, 0, newCP, 0, originalCPLength);
				newCP[originalCPLength] = ajrtLIB;
				newProject.setRawClasspath(newCP, new NullProgressMonitor());
				
			} catch (JavaModelException e) {
			}
			
			IClasspathEntry[] resolvedClasspath;
			try {
				resolvedClasspath = newProject.getResolvedClasspath(true);

				IClasspathEntry firstSourceEntry = null;
				for (IClasspathEntry classpathEntry : resolvedClasspath) {
					if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
						firstSourceEntry = classpathEntry;
						break;
					}
				}

				if (firstSourceEntry != null) {
					IPath path = ResourcesPlugin.getWorkspace().getRoot()
							.getFile(firstSourceEntry.getPath()).getLocation();

					DirTools.copyDir(LunuoLibHelper.getClientExamplesPath()
							.append(SRC).toFile(), path.toFile());

					// refresh project
					newProject.getProject()
							.refreshLocal(IResource.DEPTH_INFINITE,
									new NullProgressMonitor());

				}
			} catch (JavaModelException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return performFinish;
	}

}
